const express = require('express')
const { verifyToken, signToken } = require('../token')
const { queryUserInfo, queryUserById, userRegister, userLogin } = require('../mysql/user')
const Result = require('../result/result')
const { NO_PERMISSION } = require('../result/reponseState')

// user
const router = express.Router();

router.get('', (req, res) => {
  try {
    const token = req.get('Token')
    const decodeToken = verifyToken(token)
    queryUserInfo(decodeToken.user_phone).then((response) => {
      res.send(Result.ok(response))
    }, (err) => {
      res.send(Result.error2(NO_PERMISSION, err))
    })
  } catch (error) {
    res.send(Result.error2(NO_PERMISSION, '没有权限'))
  }
})
// 登录接口
router.post('/login', (req, res) => {
  try {
    const token = signToken(req.body)
    userLogin(req.body).then(() => {
      res.send(Result.ok(token))
    }, (err) => {
      res.send(Result.error2(NO_PERMISSION, err))
    })
  } catch (error) {
    res.send(Result.error())
  }
})
// 注册接口
router.post('/register', (req, res) => {
  userRegister(req.body).then((response) => {
    res.send(Result.ok(response))
  }, (err) => {
    res.send(Result.error2(NO_PERMISSION, err))
  })
})

module.exports = router